//
//  BaseTabBar.swift
//  app
//
//  Created by gy on 2023/7/20.
//

import Foundation

@objc protocol TabBarDelegate: NSObjectProtocol {
    
    func shouldSelect(index: Int) -> Bool
    @objc func singleTap(tabBar: BaseTabBar, index: Int)
    @objc func unselectItem(tabBar: BaseTabBar, index: Int)
    
}
class BaseTabBar: UITabBar {
    
    /// 当前选中的Item
    fileprivate var currentItem: TabBar_Item?
    weak var tabBarDelegate: TabBarDelegate?
    
    private(set) var itemModels = [TabBarItemModel]()
    private var currentIndex = 0
    
    init(frame: CGRect, itemModel: [TabBarItemModel], currentSelect: Int) {
        
        super.init(frame: frame)
        itemModels = itemModel
        currentIndex = currentSelect
        
        didinitialized()
        createAndConfigUI()
        
    }
    
    func createAndConfigUI() {
        isTranslucent = false
        backgroundColor = UIColor.white
        
        let w: CGFloat = CGFloat(ceilf(Float(CGFloat(screenWidth / CGFloat(itemModels.count)))))
        
        for (index, data) in itemModels.enumerated() {
            let item = TabBar_Item(model: data)
            item.tag = 8880+index
            item.frame = CGRect(x: CGFloat(index) * w, y: 0.0, width: w, height: CGFloat(kTabbarHeight))
            addSubview(item)
            
            item.index = index;
            item.selected = index == currentIndex;
            
            if index == currentIndex { currentItem = item }
            
            let singleTap = UITapGestureRecognizer(target: self, action: #selector(singleTap(tap:)))
            singleTap.numberOfTouchesRequired = 1
            singleTap.numberOfTapsRequired = 1
            item.addGestureRecognizer(singleTap)
        }
    }
    
    func switchItem(index: Int) {
        guard let tapGR = viewWithTag(8880+index)?.gestureRecognizers?.last as? UITapGestureRecognizer else { return }
        singleTap(tap: tapGR)
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        fatalError("init(coder:) has not been implemented")
    }
    
    func didinitialized() {
        
    }
    
}

// MARK: - TouchAction
extension BaseTabBar {
    
    /// 点击
    @objc func singleTap(tap: UITapGestureRecognizer) {
        
        let item = tap.view as! TabBar_Item
        guard item != currentItem, let d = tabBarDelegate else { return }
        
        let isContinue = d.shouldSelect(index: item.index!)
        guard isContinue == true else { return }
        
        let oldItem = currentItem
        
        currentItem?.selected = false
        item.selected = true
        currentItem = item
        
        animation(item: item)
        
        if d.responds(to: #selector(d.unselectItem(tabBar:index:))) {
            d.singleTap(tabBar: self, index: (oldItem?.index!)!)
        }
        
        if d.responds(to: #selector(d.singleTap(tabBar:index:))) {
            d.singleTap(tabBar: self, index: item.index!)
        }
        
    }
    
    /// 动画一下
    fileprivate func animation(item: TabBar_Item) {
        let pulse = CABasicAnimation(keyPath: "transform.scale")
        pulse.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
        pulse.duration = 0.2
        pulse.autoreverses = true
        pulse.fromValue = 0.9
        pulse.toValue = 1.1
        item.iconView.layer.add(pulse, forKey: nil)
    }
}


// MARK: - Override
extension BaseTabBar {
    override var items: [UITabBarItem]? {
        get { return [] }
        set {}
    }
    override func setItems(_ items: [UITabBarItem]?, animated: Bool) {
    }
}


// MARK: - 自定义`UITabBar`的按钮
class TabBar_Item: UIView {
    
    var model: TabBarItemModel?
    var index: Int?
    
    /// change UI style
    var selected: Bool = false {
        didSet {
            if selected {
                iconView.image = model!.selectedImage
                titleView.textColor = .app_tabbarSelectColor
                titleView.font = kSetPingFangBlod(12)
            } else {
                iconView.image = model!.image
                titleView.textColor = .app_tabbarUnSelectColor
                titleView.font = kSetPingFangRegular(12)
            }
        }
    }
    
    lazy var visualEffectView: UIVisualEffectView = {
        let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight))
        return visualEffectView
    }()
    lazy var iconView: UIImageView = {
        let iconView = UIImageView()
        iconView.contentMode =  .bottom
        return iconView
    }()
    
    lazy var titleView: UILabel = {
        let title = UILabel.init(frame: CGRect.zero)
        title.textAlignment = .center
        title.font = kSetPingFangRegular(12)
        title.textColor = UIColor.hex(hexString: "777A84")
        return title
    }()
    
    lazy var NumBer:UILabel = {
        let num = UILabel.init()
        num.backgroundColor = UIColor.red
        num.layer.masksToBounds = true
        num.layer.cornerRadius = 5
        return num
    }()
    /// 设置Item显示所需数据
    /// - Parameters:
    ///   - model: 数据
    func configData(model: TabBarItemModel) {
        titleView.text = model.title.localized
        iconView.image = selected ? model.selectedImage:model.image
        
        self.model = model
    }
    
    ///=============================================================================
    /// - Note: Initialization
    ///=============================================================================
    override init(frame: CGRect) {
        super.init(frame: frame)
        createUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        createUI()
    }
    
    convenience init(model: TabBarItemModel) {
        self.init(frame: .zero)
        configData(model: model)
    }
    
    func createUI() {
        backgroundColor = UIColor.white
        addSubview(visualEffectView)
        addSubview(iconView)
        addSubview(titleView)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        visualEffectView.frame = bounds
        iconView.frame = CGRect(x: 0, y: 6, width: width, height: 28)
        let y = iconView.frame.maxY + 2
        titleView.frame = CGRect(x: 0, y: y, width: width, height: 13)
    }
}


/// 一个·TabBarItem·展示所需的全部数据
struct TabBarItemModel {
    var title: String
    var image: UIImage
    var selectedImage: UIImage
    
    /// Initialization
    /// - Parameters:
    ///   - t: title
    ///   - i: image name
    ///   - s: selectedImage name
    init(t: String, i: UIImage, s: UIImage) {
        title = t
        image = i
        selectedImage = s
    }
}
